﻿using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Fee.FileAttachs;
using Fee.IO.Exporters;
using Fee.IO.Importers;
using Fee.Stores;
using Fee.ViewModel;
using JwtWebApi.Data;
using JwtWebApi.Filters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.EntityFrameworkCore;

namespace JwtWebApi.Controllers.Manage
{
    [Authorize]
    [Route("manage/[controller]")]
    [ApiController]
    [EnableCors]
    public class StationController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly FileManager _fileManager;

        public StationController(ApplicationDbContext context, FileManager fileManager)
        {
            _context = context;
            _fileManager = fileManager;
        }

        [HttpGet("list")]
        public IActionResult Index([FromQuery] StationSearcher searcher)
        {
            var query = _context.Stations
                .Include(f => f.District)
                .Include(f => f.OrderDistrict)
                .Where(f =>
                    (string.IsNullOrEmpty(searcher.StationName) || f.Name.Contains(searcher.StationName))
                    && (searcher.DistrictId == null || searcher.DistrictId == f.District.Id)
                    && (searcher.Type == null || searcher.Type == f.Type)
                    && (searcher.Status == null || searcher.Status == f.Status)
                );

            return Json(new
            {
                data = query.Skip(searcher.GetSkip()).Take(searcher.GetTake())
                    .Select(f => new StationViewModel(f)).ToList(),
                total = query.Count()
            });
        }

        [HttpPost("Save")]
        [ModelValidteFilter]
        public IActionResult Save([FromBody] StationViewModel viewModel)

        {
            var station = viewModel.ToStation(_context);
            if (station.Id != 0)
                _context.Update(station);
            else
                _context.Add(station);

            _context.SaveChanges();
            return Json(new { successed = true, message = "成功", stationId = station.Id });
        }

        [HttpGet("get/{id}")]
        public IActionResult Get(int id)
        {
            var district = _context.Stations
                .Include(f => f.District)
                .Include(f => f.OrderDistrict)
                .FirstOrDefault(_ => _.Id == id);
            return Json(new StationViewModel(district));
        }

        [HttpGet("sync/{id}")]
        public IActionResult Sync(int id)
        {
            return Json(new
            {
                successed = true,
                message = "同步完成"
            });
        }

        [HttpPut("auto-create-order")]
        public IActionResult AutoCreate()
        {
            return Json(new
            {
                successed = true,
                message = ""
            });

        }

        [HttpGet("excel")]
        public IActionResult StationExport([FromQuery] StationSearcher searcher)
        {
            var query = _context.Stations
                .Include(f => f.District)
                .Where(f =>
                    (string.IsNullOrEmpty(searcher.StationName) || f.Code.Contains(searcher.StationName))
                    && (searcher.DistrictId == null || searcher.DistrictId == f.District.Id)
                    && (searcher.Type == null || searcher.Type == f.Type)
                    && (searcher.Status == null || searcher.Status == f.Status)
                );

            var fileName = _fileManager.GetTempPrivateFile(".xlsx", this.User.Identity);
            var exportor = new StationExporter();
            var templateFile = _fileManager.GetImportTemplateFile("站点导入模板.xlsx");
            var stream = System.IO.File.OpenWrite(fileName);
            exportor.ToExcel(stream, query.ToList(),templateFile);


            return File(System.IO.File.OpenRead(fileName), "APPLICATION/octet-stream");
        }

        [HttpPost("Import")]
        public async Task<IActionResult> Post([FromForm] IFormFile formFile, [FromRoute] string type)
        {
            // full path to file in temp location
            var filePath = _fileManager.GetTempPrivateFile(Path.GetExtension(formFile.FileName), User.Identity);
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }

            var manager = new StationImporter<ApplicationDbContext>(_context);
            var importRowResults = manager.Import(filePath, out var isValidate, out var resultFilePath);

            var message = importRowResults ? "导入成功" : "导入失败";
            message += "。请点击结果文件，查看文件导入结果";
            _context.SaveChanges();
            return Json(new
            {
                successed = isValidate,
                resultFilePath,
                message
            });
        }
    }
}